
package com.oahcfly.chgame.core.mvc;

import java.util.Collection;
import java.util.HashMap;

import com.badlogic.gdx.scenes.scene2d.Action;
import com.oahcfly.chgame.core.data.CHUIData;
import com.oahcfly.chgame.core.event.CHEvent;
import com.oahcfly.chgame.core.event.CHEventManager;
import com.oahcfly.chgame.egret.ui.EXMLBaseSkinUI;

/** <pre>
 * 【Model层】
 * 涉及数据相关的所有操作全部从这个发起和更改。
 * date: 2014-12-3
 * </pre>
 * 
 * @author caohao */
public abstract class CHModel {

	public CHScreen screen;

	public CHModel () {
	}

	public CHModel (CHScreen chScreen) {
		screen = chScreen;
	}

	@SuppressWarnings("unchecked")
	public <T extends CHScreen> T getScreen () {
		return (T)screen;
	}

	public void setScreen (CHScreen screen) {
		this.screen = screen;
	}

	/** 通知UI刷新
	 * 
	 * @param uidata 携带的数据 */
	public void dispatchUIEvent (CHUIData uidata) {
		CHEvent chEvent = new CHEvent(CHEventManager.EVENT_SCREEN_UI, uidata);
		CHEventManager.getInstance().dispatchEvent(chEvent);
	}

	public void dispatchUIEvent (String actionName) {
		dispatchUIEvent(actionName, null);
	}

	public void dispatchUIEvent (String actionName, Action action) {
		CHUIData chuiData = new CHUIData(actionName, null);
		chuiData.setAction(action);
		CHEvent chEvent = new CHEvent(CHEventManager.EVENT_SCREEN_UI, chuiData);
		CHEventManager.getInstance().dispatchEvent(chEvent);
	}

	/**
	 * 发送数据变化通知
	 */
	public void notifyDataChanged () {
		Collection<EXMLBaseSkinUI> baseSkinUIs = getScreen().getBaseSkinUIMap().values();
		for (EXMLBaseSkinUI exmlBaseSkinUI : baseSkinUIs) {
			if (exmlBaseSkinUI != null && exmlBaseSkinUI.getStage() != null) {
				HashMap<String, String> dataMap = new HashMap<String, String>();
				dataMap.put("datachanged", "true");
				// 通知所有舞台内的ui
				exmlBaseSkinUI.handleUIEvent(dataMap);
			}
		}
	}
}
